﻿using BudgetManager.Data;
using BudgetManager.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BudgetManager.ViewModels
{
    public class ExpenseReportViewModel
    {
        public List<KeyedList<string, ExpenseReport>> GroupedExpenses
        {
            get
            {
                var expenses = new BudgetMgrDAL().LoadExpenses(null);
                List<ExpenseReport> expReportEntity = ConvertToExpenseReport(expenses);
                var group =
                    from expense in expReportEntity
                    group expense by expense.Category into expGroup
                    select new KeyedList<string, ExpenseReport>(expGroup);

                return new List<KeyedList<string, ExpenseReport>>(group);
            }
        }

        private List<ExpenseReport> ConvertToExpenseReport(List<Expense> expenses)
        {
            List<ExpenseReport> exp = new List<ExpenseReport>();
            foreach (var item in expenses)
            {
                ExpenseReport reptItem = new ExpenseReport() { ExpenseAmount = item.ExpenseAmount, Category = item.Category, Comments = item.Comments, Date = ((DateTime)item.ExpenseDate).Day, Month = ((DateTime)item.ExpenseDate).ToString("MMM"), Year = ((DateTime)item.ExpenseDate).Year, ExpenseId = item.ExpenseId };
                exp.Add(reptItem);
            }
            return exp;
        }

    }

    public class KeyedList<TKey, TItem> : List<TItem>
    {
        public TKey Key { protected set; get; }

        public KeyedList(TKey key, IEnumerable<TItem> items)
            : base(items)
        {
            Key = key;
        }

        public KeyedList(IGrouping<TKey, TItem> grouping)
            : base(grouping)
        {
            Key = grouping.Key;
        }
    }

}
